<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
      <!-- 警告框 -->
      <el-alert
        show-icon
        title="注意，只允许第三级分类设置相关参数!"
        type="warning"
        :closable="false"
      >
      </el-alert>
      <!-- 级联分类选择框 -->
      <el-row class="selectForm">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectParamsId"
            :options="paramsData"
            :props="paramsProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页 -->
      <el-tabs
        v-model="activeName"
        @tab-click="handleClick"
        style="text-align: left"
      >
        <el-tab-pane label="动态参数" name="many" :disabled="isTabPane">
          <el-button
            type="primary"
            size="mini"
            class="btn"
            @click="addParams"
            :disabled="isTabPane"
            >添加参数</el-button
          >
          <!-- 表格 -->
          <el-table border stripe :data="paramsList">
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="removeTag(i,scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditForm(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="only" :disabled="isTabPane">
          <el-button
            type="primary"
            size="mini"
            class="btn"
            @click="addParams"
            :disabled="isTabPane"
            >添加参数</el-button
          >
          <!-- 表格 -->
          <el-table border stripe :data="paramsList">
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="removeTag(i,scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditForm(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加参数弹框 -->
      <el-dialog
        :title="'添加' + textTitle"
        :visible.sync="isParamsDialog"
        width="50%"
        @close="reParamsForm"
      >
        <!-- 添加参数表单 -->
        <el-form
          :model="addParamsForm"
          :rules="addParamsRules"
          ref="addParamsRef"
          label-width="100px"
        >
          <el-form-item :label="textTitle" prop="attr_name">
            <el-input v-model="addParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="isParamsDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitParams">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑参数弹框 -->
      <el-dialog
        :title="'编辑' + textTitle"
        :visible.sync="isEditParamsDialog"
        width="50%"
        @close="reEditParamsForm"
      >
        <!-- 编辑参数表单 -->
        <el-form
          :model="editParamsForm"
          :rules="editParamsRules"
          ref="editParamsRef"
          label-width="100px"
        >
          <el-form-item :label="textTitle" prop="attr_name">
            <el-input v-model="editParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="isEditParamsDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitEditParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      paramsData: [],
      paramsProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
        expandTrigger: "hover",
      },
      selectParamsId: [],
      activeName: "many",
      isTabPane: true,
      paramsList: [],
      isParamsDialog: false,
      addParamsForm: {
        attr_name: "",
      },
      addParamsRules: {
        attr_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          {
            min: 2,
            max: 15,
            message: "长度在 2 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
      isEditParamsDialog: false,
      editParamsForm: {
        attr_name: "",
      },
      editParamsRules: {
        attr_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          {
            min: 2,
            max: 15,
            message: "长度在 2 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    //计算添加参数表头
    textTitle: function () {
      if (this.activeName == "many") {
        return "动态参数";
      } else {
        return "静态参数";
      }
    },
  },
  methods: {
    //级联选择器，是否第三级分类，禁用启用
    handleChange() {
      console.log(this.selectParamsId);
      if (this.selectParamsId.length === 3) {
        this.isTabPane = false;
        this.getParamsList();
        return;
      }
      //禁用
      this.selectParamsId = [];
      this.isTabPane = true;
      this.paramsList = [];
    },
    //获取商品分类数据
    async getCateList() {
      let { data: res } = await this.$http.get("categories");
      if (res.meta.status != 200) return this.$message.error("获取数据失败");
      console.log(res);
      this.paramsData = res.data;
    },
    //tag标签页时间事件
    handleClick() {
      this.getParamsList();
    },
    //获取参数列表
    async getParamsList() {
      let {
        data: res,
      } = await this.$http.get(
        `categories/${this.selectParamsId[2]}/attributes`,
        { params: { sel: this.activeName } }
      );
      if (res.meta.status != 200) return this.$message.error("获取数据失败");
      console.log(res);

      //将attr_vals以空格分割成数组
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];

        //为每项设置显示隐藏属性
        item.inputVisible = false;
        item.inputValue = "";
      });

      this.paramsList = res.data;
    },
    //显示表单
    addParams() {
      this.isParamsDialog = true;
    },
    //重置表单
    reParamsForm() {
      this.$refs.addParamsRef.resetFields();
    },
    reEditParamsForm() {
      this.$refs.editParamsRef.resetFields();
    },
    //添加参数
    submitParams() {
      this.$refs.addParamsRef.validate(async (vaild) => {
        let {
          data: res,
        } = await this.$http.post(
          `categories/${this.selectParamsId[2]}/attributes`,
          { attr_name: this.addParamsForm.attr_name, attr_sel: this.activeName }
        );
        console.log(res);
        if (res.meta.status != 201) return this.$message.error("获取数据失败");
        this.$message.success("添加参数成功");
        this.isParamsDialog = false;
        this.getParamsList();
      });
    },
    //显示编辑弹框，获取参数数据
    async showEditForm(attrId) {
      let {
        data: res,
      } = await this.$http.get(
        `categories/${this.selectParamsId[2]}/attributes/${attrId}`,
        { params: { attr_sel: this.activeName } }
      );
      if (res.meta.status != 200) return this.$message.error("获取数据失败");
      console.log(res);
      this.editParamsForm = res.data;
      this.isEditParamsDialog = true;
    },
    //修改参数属性
    submitEditParams() {
      this.$refs.editParamsRef.validate(async (vaild) => {
        if (!vaild) return;
        let { data: res } = await this.$http.put(
          `categories/${this.selectParamsId[2]}/attributes/
      ${this.editParamsForm.attr_id}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        console.log(res);
        if (res.meta.status != 200) return this.$message.error("修改参数失败");
        this.$message.success("修改参数成功");
        this.isEditParamsDialog = false;
        this.getParamsList();
      });
    },
    //删除参数
    removeParams(attrid) {
      this.$confirm("此操作将永久删除该参数, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .catch((err) => err)
        .then(async (confirm) => {
          console.log(confirm);
          if (confirm != "confirm") return this.$message.info("取消删除");
          let { data: res } = await this.$http.delete(
            `categories/${this.selectParamsId[2]}/attributes/${attrid}`
          );
          if (res.meta.status != 200) return this.$message.error("删除失败");
          this.$message.success("删除成功");
          this.getParamsList();
        });
    },
    //监听input，添加标签
    handleInputConfirm(role) {
      if(role.inputValue.trim().length == 0){
        role.inputValue = ""
        role.inputVisible = false;
        return
      }

      role.attr_vals.push(role.inputValue.trim())
      role.inputValue = ""
      role.inputVisible = false;

      this.editTag(role)

    },
    //修改标签页
    async editTag(role){
      let {data:res} = await this.$http.put(`categories/${this.selectParamsId[2]}/attributes/${role.attr_id}`,
      {attr_name: role.attr_name,
       attr_sel: this.activeName,
       //role.attr_vals需要转为字符串
       attr_vals: role.attr_vals.join(" ") 
      })
      if(res.meta.status != 200) return this.$message.error("获取数据失败")
      this.$message.success("修改标签成功")
    },
    //删除标签
    removeTag(i,role){
       role.attr_vals.splice(i,1)
       this.editTag(role)
    },
    showInput(role) {
      role.inputVisible = true;
      //自动获取光标
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
  },
  created() {
    this.getCateList();
  },
};
</script>

<style lang="less" scoped>
.selectForm {
  text-align: left;
  margin-top: 15px;
  font-size: 14px;
}
.btn {
  margin-bottom: 15px;
}
.el-table {
  font-size: 12px;
}
/deep/ .el-table__expanded-cell[class*="cell"] {
  padding: 20px 10px;
}
.el-tag {
  margin-right: 10px;
  margin-bottom: 10px;
}
.el-input {
  width: 120px;
}
</style>